<?php

namespace App\Controller\Api;

use App\Base\BaseController4Restful;
use App\Entity\ShopAuth;
use App\Repository\ShopAuthRepository;
use App\Service\ShopService;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class ApiShopAuthController extends BaseController4Restful
{
    /**
     * @Route("/api/shopAuths", name="apiGetShopAuths",methods={"GET","POST"})
     */
    public function apiGetShopAuths(ShopAuthRepository $repository,Request $request)
    {
        switch ($request->getMethod()) {
            case "POST":
                $user = $this->needToBeUser();
                $data = $this->getRequestData();
                $data["code"] .="";
                /**@var $ShopAuth ShopAuth*/
                $ShopAuth = $this->createEntity($data,ShopAuth::class);
                $ShopAuth->setStatus(0)
                    ->setShop($user->getShop())
                    ->setCreateAt(new \DateTime());
                $this->myEm()->persist($ShopAuth);$this->myEm()->flush();
                return $this->json_out(200,"已提交", $ShopAuth);
            default:
                $user = $this->needToBeUser();
                if (!$page = $this->getParamRequired("page")) {$page = 1;}
                $limit = 10;
                $offset = (int)abs($limit * ($page - 1));
                $total = $repository->count([]);
                $this->setMeta($page,$total,$limit);
                $list = $repository->findBy(array("shop"=>$user->getShop()),array("id"=>"DESC"),$limit,$offset);
                return $this->json_out(200,"获取成功", $list);
        }
    }

    /**
     * @Route("/api/shopAuths/{id}", name="apiAddShopAuths",methods={"GET","PUT","PATCH","DELETE"})
     */
    public function apiUpdateShopAuths(ShopAuth $ShopAuth,Request $request,ShopService $shopService)
    {
        $data = $this->getRequestData();
        switch ($request->getMethod()) {
            case "DELETE":
                $this->myEm()->remove($ShopAuth);$this->myEm()->flush();
                return $this->json_out(200,"已移除");
            case "PATCH":
            case "PUT":
                /**@var $ShopAuth ShopAuth*/
                $startStatus = $ShopAuth->getStatus();
                $ShopAuth = $this->updateEntity($data,ShopAuth::class,$ShopAuth);
                $endStatus = $ShopAuth->getStatus();
                if ($request->getMethod() == "PATCH" && $startStatus == 0 && $endStatus == 1) {
                    //检查用户是否有相应标签，如果没有就增加
                    $shop = $ShopAuth->getShop();
                    if (!$shopService->hasTag($shop,ShopService::__TAG_COMPANY__)) {
                        $shopService->addTagId($shop,ShopService::__TAG_COMPANY__);
                    }
                }
                break;
            case "Get":
            default:
        }
        $this->myEm()->persist($ShopAuth);$this->myEm()->flush();
        return $this->json_out(200,"获取成功", $ShopAuth);
    }
}
